<?php

/**
 * 基础控制器
 */

namespace app\topics\middle;


class RegisterMiddle extends \app\base\middle\BaseMiddle {


    private $config = [];

    /**
     * 媒体信息
     */
    protected function meta() {
        $this->setMeta('注册');
        $this->setName('注册');
        $this->setCrumb([
            [
                'name' => '注册',
                'url' => url()
            ]
        ]);

        return $this->run([
            'pageInfo' => $this->pageInfo
        ]);
    }

    protected function post() {
        $model = target('topics/TopicsUser');
        $model->beginTransaction();
        $userName = $this->params['username'];
        $password = $this->params['password'];
        if (empty($userName) || empty($password)) {
            return $this->stop('用户名或密码未填写！');
        }
        $imgCode = new \dux\lib\Vcode(90, 37, 4, '', 'code');
        if (!$imgCode->check($this->params['imgcode'])) {
            return $this->stop('图片验证码输入不正确!');
        }

        $userName = trim($userName);
        if(strlen($userName) < 2 || strlen($userName) > 18) {
            return $this->stop('用户名必须为2-12个字符！');
        }

        $password = trim($password);
        if(strlen($password) < 6 || strlen($password) > 18) {
            return $this->stop('密码必须为6-12个字符！');
        }

        $info = $model->getWhereInfo([
            'username' => $userName
        ]);
        if (!empty($info)) {
            return $this->stop('该用户已被注册!');
        }

        $model->beginTransaction();
        $data = array();
        $data['role_id'] = 1;
        $data['username'] = $userName;
        $data['password'] = md5($password);
        $data['reg_time'] = time();
        $data['login_time'] = time();
        $data['login_ip'] = \dux\lib\Client::getUserIp();
        $userId = $model->add($data);
        if (!$userId) {
            return $this->stop($model->getError());
        }
        $model->commit();
        $config = \dux\Config::get('dux.use');
        $loginData = array();
        $loginData['uid'] = $userId;
        $loginData['token'] = sha1(md5($password) . $config['safe_key']);
        return $this->run($loginData);
    }

    protected function getCode() {
        $config = $this->getConfig();
        $imgCode = new \dux\lib\Vcode(90, 37, 4, '', 'code');
        if (!$imgCode->check($this->params['imgcode']) && $config['verify_image']) {
            return $this->stop('图片验证码输入不正确!');
        }
        if (!target('member/Member', 'service')->getVerify($this->params['username'])) {
            return $this->stop(target('member/Member', 'service')->getError());
        }
        return $this->run();
    }

}